<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import {
  altStatusUsingPut,
  delProductUsingDelete,
  listProductsByPageUsingPost,
} from '@/api/productController.ts'
import { STATUS_TYPE_OPTIONS } from '@/constants/product.ts'
import { PlusOutlined } from '@ant-design/icons-vue'
import ProductAddView from '@/views/product/ProductAddView.vue'
import ProductUpdateView from '@/views/product/ProductUpdateView.vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    align: 'center',
  },
  {
    title: '名称',
    dataIndex: 'name',
    align: 'center',
  },
  {
    title: '图片',
    dataIndex: 'image',
    align: 'center',
  },
  {
    title: '描述',
    dataIndex: 'description',
    align: 'center',
  },
  {
    title: '价格',
    dataIndex: 'price',
    align: 'center',
  },
  {
    title: '库存',
    dataIndex: 'stock',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
  },
]

// 数据
const tableData = ref<API.Product[]>([])
const total = ref<number>(0)

// 搜索条件
const searchParams = ref<API.PageProductDto>({
  current: 1,
  pageSize: 10,
})

// 模态框控制器
const modalOpen = ref<boolean>(false)
const modalAddOpen = ref<boolean>(false)

// ref对象
const productUpdateRef = ref()
const productAddRef = ref()

// 关闭模态框
const closeModal = () => {
  modalOpen.value = false
}
const closeAddModal = () => {
  modalAddOpen.value = false
}

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.value.current ?? 1,
    pageSize: searchParams.value.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 加载数据
const loadData = async () => {
  const res = await listProductsByPageUsingPost({
    ...searchParams.value,
  })
  if (res.code === 200 && res.data) {
    tableData.value = res.data.records
    total.value = res.data.total
  } else {
    message.error(res.message)
  }
}

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.value.current = page.current
  searchParams.value.pageSize = page.pageSize
  loadData()
}

// 搜索
const doSearch = () => {
  searchParams.value.current = 1
  loadData()
}

// 重置
const doReset = () => {
  searchParams.value = {
    current: 1,
    pageSize: 10,
  }
  loadData()
}

// 删除
const doDelete = async (id: string) => {
  if (!id) {
    return
  }
  const res = await delProductUsingDelete({
    id: id,
  })
  if (res.code === 200) {
    message.success('删除成功')
    await loadData()
  } else {
    message.error(res.message)
  }
}

// 编辑
const doEdit = (id: number) => {
  modalOpen.value = true
  productUpdateRef.value.getProductInfo(id)
}

// 新增商品
const doAdd = () => {
  modalAddOpen.value = true
}

// 修改商品状态
const doAlterStatus = async (id: string, status: number) => {
  if (!id) {
    return
  }
  const res = await altStatusUsingPut({
    id: id,
    status: status,
  })
  if (res.code === 200 && res.data) {
    message.success('修改成功')
    await loadData()
  } else {
    message.error(res.message)
  }
}

// 批量新增
const doBatchAdd = () => {
  router.push('/product/batch-add')
}

onMounted(() => loadData())
</script>

<template>
  <div id="product-manage-view">
    <a-form layout="inline" :model="searchParams" @finish="doSearch" style="margin-bottom: 20px">
      <a-form-item label="名称">
        <a-input v-model:value="searchParams.name" placeholder="请输入名称" allow-clear />
      </a-form-item>
      <a-form-item label="状态">
        <a-select
          v-model:value="searchParams.status"
          :options="STATUS_TYPE_OPTIONS"
          placeholder="请选择状态"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
        <a-button style="margin-left: 10px; background-color: grey; color: white" @click="doReset"
          >重置
        </a-button>
      </a-form-item>
      <a-space style="margin-left: auto">
        <a-button @click="doBatchAdd">批量新增</a-button>
        <a-button type="primary" ghost @click="doAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          新增商品
        </a-button>
      </a-space>
    </a-form>
    <a-table
      :data-source="tableData"
      :columns="columns"
      :pagination="pagination"
      @change="doTableChange"
      :scroll="{ x: 1800 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'image'">
          <a-image :src="record.image" :width="60" />
        </template>
        <template v-if="column.dataIndex === 'status'">
          <div v-if="record.status === 0">
            <a-tag color="green">上架</a-tag>
          </div>
          <div v-else>
            <a-tag color="red">下架</a-tag>
          </div>
        </template>
        <template v-if="column.key === 'action'">
          <a-button type="link" @click="doEdit(record.id)"> 编辑</a-button>
          <a-button
            v-if="record.status === 0"
            type="link"
            danger
            @click="doAlterStatus(record.id, 1)"
          >
            下架
          </a-button>
          <a-button v-if="record.status === 1" type="link" @click="doAlterStatus(record.id, 0)">
            上架
          </a-button>
          <a-popconfirm
            title="确定删除这条记录吗？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="doDelete(record.id)"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <product-add-view
      ref="productAddRef"
      :is-open="modalAddOpen"
      :close-modal="closeAddModal"
      :refresh-data="loadData"
    />
    <product-update-view
      ref="productUpdateRef"
      :is-open="modalOpen"
      :close-modal="closeModal"
      :refresh-data="loadData"
    />
  </div>
</template>

<style scoped></style>
